# -*- coding: utf-8 -*-
"""
购物车控制层

负责处理购物车、地址、库存等相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends, Query, Body, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from app.services.cart_service import CartService, AddressService, StockService
from app.controllers.user_controller import get_current_user

# 创建路由
cart_router = APIRouter(
    prefix="/cart",
    tags=["cart"],
    responses={404: {"description": "Not found"}}
)

address_router = APIRouter(
    prefix="/addresses",
    tags=["addresses"],
    responses={404: {"description": "Not found"}}
)

stock_router = APIRouter(
    prefix="/stock",
    tags=["stock"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
cart_service = CartService()
address_service = AddressService()
stock_service = StockService()

# Pydantic 模型
class AddToCartRequest(BaseModel):
    goods_id: str = Field(..., description="商品ID")
    spec_id: str = Field(..., description="规格ID")
    quantity: int = Field(1, gt=0, description="数量")

class UpdateCartRequest(BaseModel):
    quantity: Optional[int] = Field(None, gt=0, description="更新数量")
    is_selected: Optional[bool] = Field(None, description="是否选中")

class BatchDeleteCartRequest(BaseModel):
    cart_ids: List[str] = Field(..., description="要删除的购物车商品ID列表")

class AddressRequest(BaseModel):
    receiver_name: str = Field(..., description="收货人姓名")
    receiver_phone: str = Field(..., description="收货人手机")
    province: str = Field(..., description="省份")
    city: str = Field(..., description="城市")
    district: str = Field(..., description="区县")
    detail_address: str = Field(..., description="详细地址")
    postal_code: Optional[str] = Field(None, description="邮政编码")
    is_default: Optional[bool] = Field(False, description="是否默认地址")
    address_tag: Optional[str] = Field("", description="地址标签")


# =========================== 购物车相关接口 ===========================

@cart_router.post("/add")
async def add_to_cart(request: AddToCartRequest, current_user = Depends(get_current_user)):
    """添加商品到购物车"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.add_to_cart(
            user_id, request.goods_id, request.spec_id, request.quantity
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result.get('data')
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加到购物车失败: {str(e)}")


@cart_router.get("/list")
async def get_cart_list(current_user = Depends(get_current_user)):
    """获取购物车列表"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.get_cart_list(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取购物车失败: {str(e)}")


@cart_router.put("/{cart_id}")
async def update_cart_item(
    cart_id: str, 
    request: UpdateCartRequest, 
    current_user = Depends(get_current_user)
):
    """更新购物车商品"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.update_cart_item(
            cart_id, user_id, request.quantity, request.is_selected
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新购物车失败: {str(e)}")


@cart_router.delete("/{cart_id}")
async def remove_from_cart(cart_id: str, current_user = Depends(get_current_user)):
    """从购物车移除商品"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.remove_from_cart(cart_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"移除商品失败: {str(e)}")


@cart_router.post("/delete")
async def batch_remove_from_cart(request: BatchDeleteCartRequest, current_user = Depends(get_current_user)):
    """批量删除购物车商品"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.remove_multiple_from_cart(request.cart_ids, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量删除商品失败: {str(e)}")


@cart_router.delete("/clear")
async def clear_cart(
    selected_only: bool = Query(False, description="是否只清空选中商品"),
    current_user = Depends(get_current_user)
):
    """清空购物车"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.clear_cart(user_id, selected_only)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"清空购物车失败: {str(e)}")


# =========================== 收货地址相关接口 ===========================

@address_router.get("/list")
async def get_user_addresses(current_user = Depends(get_current_user)):
    """获取用户收货地址列表"""
    try:
        user_id = current_user.get('user_id')
        result = address_service.get_user_addresses(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址列表失败: {str(e)}")


@address_router.post("/create")
async def create_address(request: AddressRequest, current_user = Depends(get_current_user)):
    """创建收货地址"""
    try:
        user_id = current_user.get('user_id')
        address_data = request.dict()
        result = address_service.create_address(user_id, address_data)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建地址失败: {str(e)}")


@address_router.put("/{address_id}")
async def update_address(
    address_id: str, 
    request: AddressRequest, 
    current_user = Depends(get_current_user)
):
    """更新收货地址"""
    try:
        user_id = current_user.get('user_id')
        address_data = request.dict()
        result = address_service.update_address(address_id, user_id, address_data)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新地址失败: {str(e)}")


@address_router.delete("/{address_id}")
async def delete_address(address_id: str, current_user = Depends(get_current_user)):
    """删除收货地址"""
    try:
        user_id = current_user.get('user_id')
        result = address_service.delete_address(address_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除地址失败: {str(e)}")


@address_router.post("/{address_id}/set-default")
async def set_default_address(address_id: str, current_user = Depends(get_current_user)):
    """设置默认地址"""
    try:
        user_id = current_user.get('user_id')
        result = address_service.set_default_address(address_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置默认地址失败: {str(e)}")


# =========================== 库存相关接口 ===========================

@stock_router.get("/check")
async def check_stock(
    goods_id: str = Query(..., description="商品ID"),
    spec_id: str = Query(..., description="规格ID"),
    quantity: int = Query(..., gt=0, description="数量")
):
    """检查库存"""
    try:
        result = stock_service.check_stock_available(goods_id, spec_id, quantity)
        
        if result['success']:
            return {
                "code": 200,
                "message": "检查完成",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"检查库存失败: {str(e)}")


@stock_router.get("/{goods_id}/{spec_id}")
async def get_goods_stock(goods_id: str, spec_id: str):
    """获取商品库存信息"""
    try:
        result = stock_service.get_goods_stock(goods_id, spec_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取库存信息失败: {str(e)}")


# =========================== 兼容老版本API（UniApp） ===========================

# 创建UniApp兼容路由
uniapp_cart_router = APIRouter(
    prefix="/uniapp/cart",
    tags=["uniapp-cart"],
    responses={404: {"description": "Not found"}}
)

@uniapp_cart_router.post("/add")
async def uniapp_add_to_cart(request: AddToCartRequest, current_user = Depends(get_current_user)):
    """UniApp添加商品到购物车"""
    return await add_to_cart(request, current_user)

@uniapp_cart_router.get("/list")
async def uniapp_get_cart_list(current_user = Depends(get_current_user)):
    """UniApp获取购物车列表"""
    return await get_cart_list(current_user) 

@uniapp_cart_router.post("/delete")
async def uniapp_batch_remove_from_cart(request: Request, current_user = Depends(get_current_user)):
    """UniApp批量删除购物车商品（支持直接数组格式）"""
    try:
        import json
        
        # 获取原始请求体
        body = await request.body()
        data = json.loads(body)
        
        # 处理不同的数据格式
        if isinstance(data, list):
            # 直接数组格式: ["id1", "id2", ...]
            cart_ids = data
        elif isinstance(data, dict) and 'cart_ids' in data:
            # 对象格式: {"cart_ids": ["id1", "id2", ...]}
            cart_ids = data['cart_ids']
        else:
            raise HTTPException(status_code=400, detail="无效的请求格式")
        
        user_id = current_user.get('user_id')
        result = cart_service.remove_multiple_from_cart(cart_ids, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="无效的JSON格式")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量删除商品失败: {str(e)}")

@uniapp_cart_router.post("/batch-delete")
async def uniapp_batch_remove_from_cart_object(request: BatchDeleteCartRequest, current_user = Depends(get_current_user)):
    """UniApp批量删除购物车商品（对象格式）"""
    try:
        user_id = current_user.get('user_id')
        result = cart_service.remove_multiple_from_cart(request.cart_ids, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量删除商品失败: {str(e)}")

@uniapp_cart_router.post("/delete-items")
async def uniapp_batch_remove_from_cart_array(request: Request, current_user = Depends(get_current_user)):
    """UniApp批量删除购物车商品（专门处理数组格式）"""
    try:
        import json
        
        # 获取原始请求体
        body = await request.body()
        cart_ids = json.loads(body)
        
        # 确保是数组格式
        if not isinstance(cart_ids, list):
            raise HTTPException(status_code=400, detail="请求体必须是字符串数组")
        
        user_id = current_user.get('user_id')
        result = cart_service.remove_multiple_from_cart(cart_ids, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="无效的JSON格式")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量删除商品失败: {str(e)}") 